<?php
namespace app\manage\controller;
use app\manage\controller\Base;
use app\manage\validate\AdminValidate;
use think\facade\Db;
use support\View;
use support\think\Cache;
use app\model\AuthGroupModel;
use app\model\AdminModel;
use support\Request;

class AdminController extends Base
{
    public function index(Request $request)
    {
        $key=$request->input('key','');
        $data=AdminModel::alias('a')
        ->join('auth_group w','a.role = w.id', 'LEFT')
        ->where('username','like','%'.$key.'%')
        ->order('a.id','desc')->field( 'a.id,username,w.title,a.create_time,a.update_time,a.desc,a.isopen' )->paginate(['list_rows'=>10,'query'=>request()->all()]);
        View::assign('data',$data);
        View::assign('count1', $data->total());
    	return view('admin/index');
    }
	public function ajax(Request $request)
    {
    	$data=$request->post();
		if($data['type']=='admin_start'){
			if(AdminModel::update(['isopen' => 1], ['id' => $data['id']])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
       	if($data['type']=='admin_stop' and $data['id'] != 1){
			if(AdminModel::update(['isopen' => 0], ['id' => $data['id']])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
		if($data['type']=='admin_del' and $data['id'] != 1){
			if(AdminModel::destroy($data['id'])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
		if($data['type']=='admin_all'){
			if(in_array("1", $data['id'])){
                return json(['code' => 0, 'message' => '操作失败']);
			}
			if(AdminModel::destroy($data['id'])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
        return json(['code' => 0, 'message' => '失败']);
    }
    public function add(Request $request)
    {
        if(request()->method()=='POST'){
            $data=$request->post();
            $validate = new AdminValidate();
            if(!$validate->check($data)){
                return view_e($validate->getError());
            }
            $shield=Db::name('shield')->where('id',1)->value('shield');
            if(\in_array($data['username'],explode("|",$shield))){
                return view_e('用户名非法');
            }
            $arr=$this->checkWeakPassword($data['password']);
            if($arr['valid']==false){
                return view_e($arr['message']);
            }
            $data['password']=md5(substr(md5($data['password']),0,25).'lizhili');

            $info=AdminModel::create($data);
            if($info){
                return view_s('添加成功',url('admin/index',['st'=>1]));
            }else{
                return view_e('添加失败了');
            }
        }
        $res=AuthGroupModel::where('isopen',1)->select();
        View::assign('res',$res);
        return view('admin/add');
    }
	public function edit(Request $request)
    {
    	if(request()->method()=='POST'){
    		$data=$request->post();
			$validate = new \app\manage\validate\AdminValidate();
			if(!$validate->scene('edit')->check($data)){
				return view_e($validate->getError());
			}

			if($data['password']!=''){
                $arr=$this->checkWeakPassword($data['password']);
                if($arr['valid']==false){
                    return view_e($arr['message']);
                }


				$data['password']=md5(substr(md5($data['password']),0,25).'lizhili');
			}else{
				unset($data['password']);
			}
			if(AdminModel::update($data, ['id'=>$data['id']])){
				return view_s('修改成功',url('admin/index',['st'=>1]));
			}else{
				return view_e('修改失败了');
			}
    	}
		$cid=$request->input('id',0);
		$data=AdminModel::where('id',$cid)->field('id,username,desc,role')->find();
        View::assign('data',$data);
		$res=AuthGroupModel::where('isopen',1)->select();
        View::assign('res',$res);
       return view('admin/edit');
    }
	//清除缓存
	public function cahe(Request $request){
		if(Cache::clear()){
			return view_s('清除缓存成功',url('index/main'));
		}else{
			return view_e('清除缓存失败了');
		}
	}
    protected function checkWeakPassword(string $password, array $options = []): array {
        // 默认配置（可根据需求调整）
        $defaultOptions = [
            'min_length' => 8,          // 最小长度
            'check_common' => true,     // 是否检测常见弱密码
            'check_repeats' => true,    // 是否检测重复字符
            'check_sequences' => true,  // 是否检测连续字符（数字/字母）
            'check_keyboard' => true,   // 是否检测键盘序列
        ];
        $options = array_merge($defaultOptions, $options);

        // 1. 检测长度
        if (strlen($password) < $options['min_length']) {
            return [
                'valid' => false,
                'message' => "密码长度至少需要 {$options['min_length']} 位"
            ];
        }

        // 2. 检测常见弱密码（不区分大小写）
        if ($options['check_common']) {
            $commonPasswords = [
                '123456', 'password', '123456789', '12345678', '12345',
                '111111', '1234567', 'admin', 'welcome', 'letmein', 'monkey',
                'dragon', '123123', 'baseball', 'iloveyou', 'trustno1'
            ];
            $lowerPassword = strtolower($password);
            if (in_array($lowerPassword, $commonPasswords)) {
                return ['valid' => false, 'message' => "密码过于常见，请更换"];
            }
        }

        // 3. 检测字符类型单一性（数字、小写字母、大写字母、特殊符号）
        if ($options['check_repeats']) {
            $types = [];
            if (preg_match('/\d/', $password)) $types[] = '数字';
            if (preg_match('/[a-z]/', $password)) $types[] = '小写字母';
            if (preg_match('/[A-Z]/', $password)) $types[] = '大写字母';
            if (preg_match('/[^a-zA-Z0-9]/', $password)) $types[] = '特殊符号';

            // 若类型少于 2 种，认为单一
            if (count($types) < 2) {
                return ['valid' => false, 'message' => "密码需包含至少 2 种字符类型（数字、字母、特殊符号）"];
            }
        }

        // 4. 检测连续/重复字符（如 aaaa、1234）
        if ($options['check_sequences']) {
            // 重复字符（4 次及以上）
            if (preg_match('/(.)\1{3,}/', $password)) {
                return ['valid' => false, 'message' => "密码不能包含连续 4 个以上相同字符"];
            }
            // 连续数字（升序/降序，4 位及以上）
            if (preg_match('/(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){3,}\d/', $password)) {
                return ['valid' => false, 'message' => "密码不能包含连续升序数字（如 1234）"];
            }
            if (preg_match('/(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){3,}\d/', $password)) {
                return ['valid' => false, 'message' => "密码不能包含连续降序数字（如 4321）"];
            }
            // 连续字母（升序/降序，4 位及以上，不区分大小写）
            $lowerPassword = strtolower($password);
            if (preg_match('/(?:a(?=b)|b(?=c)|c(?=d)|d(?=e)|e(?=f)|f(?=g)|g(?=h)|h(?=i)|i(?=j)|j(?=k)|k(?=l)|l(?=m)|m(?=n)){3,}[a-z]/', $lowerPassword)) {
                return ['valid' => false, 'message' => "密码不能包含连续升序字母（如 abcd）"];
            }
            if (preg_match('/(?:z(?=y)|y(?=x)|x(?=w)|w(?=v)|v(?=u)|u(?=t)|t(?=s)|s(?=r)|r(?=q)|q(?=p)|p(?=o)|o(?=n)|n(?=m)){3,}[a-z]/', $lowerPassword)) {
                return ['valid' => false, 'message' => "密码不能包含连续降序字母（如 dcba）"];
            }
        }

        // 5. 检测键盘序列（如 qwerty、asdfgh）
        if ($options['check_keyboard']) {
            $keyboardRows = [
                'qwertyuiop', 'asdfghjkl', 'zxcvbnm'  // 键盘前三行
            ];
            $lowerPassword = strtolower($password);
            foreach ($keyboardRows as $row) {
                // 检测连续 4 个及以上字符（如 qwert、asdfg）
                for ($i = 0; $i <= strlen($row) - 4; $i++) {
                    $sequence = substr($row, $i, 4);
                    if (strpos($lowerPassword, $sequence) !== false) {
                        return ['valid' => false, 'message' => "密码不能包含键盘连续序列（如 {$sequence}）"];
                    }
                }
            }
        }

        // 所有检测通过
        return ['valid' => true, 'message' => '密码符合要求'];
    }
}
